<?php
namespace app\api\controller;
/**
 * 支付宝支付回调类
 * The file is part of the payment lib.
 * (c) Leo <dayugog@gmail.com>
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
use think\facade\Db;

/**
 * Class TestNotify
 * @author  : helei
 * @date    : 2020/2/1 3:56 下午
 * @version : 1.0.0
 * @desc    : 测试异步通知
 *
 */
class wxNotify implements \Payment\Contracts\IPayNotify
{
 
    /**
     * @param string $channel 通知的渠道，如：支付宝、微信、招商
     * @param string $notifyType 通知的类型，如：支付、退款
     * @param string $notifyWay 通知的方式，如：异步 async，同步 sync
     * @param array $notifyData 通知的数据
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle(
        string $channel,
        string $notifyType,
        string $notifyWay,
        array $notifyData
    ) {
//        $this->fileinput(json_encode($notifyData));die;
        if ($notifyData['return_code'] == 'SUCCESS'){
            $order = Db::name('orders')->where('id',$notifyData['out_trade_no'])->find();
            if ($order['status'] == 2){
                return true;
            }
            // 启动事务
            Db::startTrans();
            try {
                // 修改支付状态
                $logData = [
                    'status' => 2,
                    'pay_type' => 1,
                    'pay_time' => toDate(time())
                ];
                Db::name('orders')->where('id', $order['id'])->update($logData);
                $moneyLog = [
                    'user_id' => $order['user_id'],
                    'money' => $order['total_price'],
                    'type' => 1,
                    'status' => 1,
                    'create_time' => toDate(time())
                ];
                Db::name('money_log')->insert($moneyLog);
                // 提交事务
                Db::commit();
                return true;
            } catch (\Exception $e) {
                // 回滚事务
                self::fileinput($e->getMessage());
                Db::rollback();
                return false;
            }
        }else{
            return false;
        }
    }


    public function fileinput($str='测试数据:')
    {
        $date = date('Y-m-d H:i:s');
        $content = "执行日期notify：".$date."\n".$str."\n\n";
        file_put_contents('wxNotify.log', $content);
    }

}
